<script setup>
import api from '../api/match_api.js'
import stadiumAPI from '../api/stadium_api.js'
import { ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import lodash from 'lodash'

// 表格数据与分页
const tableData = ref([])
const total = ref(0);

// 对话框状态
const editWinVisible = ref(false);
const addWinVisible = ref(false);

// 场馆列表数据
const stadiums = ref([]);

// 查询参数
const searchObj = ref({
  current: 1,
  limit: 10,
  name: '',
  stadiumId: '',
  teama: '',
  teamb: '',
  status: ''
});

// 表单数据
const obj = ref({});
const addFormRef = ref(null);
const editFormRef = ref(null);

// 新增：图片上传处理
const handleUploadSuccess = (response) => {
  obj.value.mimg = response.data;
};

// 数据加载
const search = async () => {
  try {
    const result = await api.page(searchObj.value);
    tableData.value = result.records;
    total.value = result.total;
  } catch (err) {
    ElMessage.error('数据加载失败');
  }
};

// 加载场馆列表
const loadStadiums = async () => {
  try {
    const result = await stadiumAPI.all();
    stadiums.value = result || [];
  } catch (err) {
    ElMessage.error('加载场馆列表失败');
  }
};

onMounted(async () => {
  await search();
  await loadStadiums();
});

// 分页与查询
const handleSizeChange = () => search();
const handleCurrentChange = () => search();
const handlerSearch = () => {
  searchObj.value.current = 1;
  search();
};

// 新增操作
const handleAdd = async () => {
  obj.value = { status: 1 };  // 默认状态为1
  addWinVisible.value = true;
};

const addCommit = async () => {
  try {
    await api.add(obj.value);
    ElMessage.success('新增成功');
    addWinVisible.value = false;
    search();
    obj.value = {};
  } catch (err) {
    ElMessage.error(err.message || '新增失败');
  }
};

// 编辑操作
const handleEdit = async (_, row) => {
  obj.value = lodash.clone(row);
  editWinVisible.value = true;
};

const editCommit = async () => {
  try {
    await api.edit(obj.value);
    ElMessage.success('编辑成功');
    editWinVisible.value = false;
    search();
  } catch (err) {
    ElMessage.error(err.message || '编辑失败');
  }
};

// 删除操作
const handleDelete = (_, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗？',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  ).then(async () => {
    try {
      await api.del(row.id);
      ElMessage.success('删除成功');
      search();
    } catch (err) {
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

// 取消操作
const editCancel = () => {
  obj.value = {};
  editWinVisible.value = false;
};
const addCancel = () => {
  obj.value = {};
  addWinVisible.value = false;
};

// 状态文本转换方法
const getStatusName = (status) => {
  switch(status) {
    case 0: return '未开始';
    case 1: return '进行中';
    default: return '未知状态';
  }
};

// 根据场馆ID获取场馆名称
const getStadiumName = (id) => {
  if (!id) return '未选择';
  const stadium = stadiums.value.find(item => item.id === id);
  return stadium ? stadium.name : '未知场馆';
};
</script>

<template>
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px ">
    <el-form-item label="赛事名称">
      <el-input v-model="searchObj.name" placeholder="请输入赛事名称" clearable />
    </el-form-item>
    <el-form-item label="场馆">
      <el-select
          v-model="searchObj.stadiumId"
          placeholder="请选择场馆"
          clearable
          filterable
          style="width: 200px"
      >
        <el-option
            v-for="item in stadiums"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="A队">
      <el-input v-model="searchObj.teama" placeholder="请输入A队名称" clearable />
    </el-form-item>
    <el-form-item label="B队">
      <el-input v-model="searchObj.teamb" placeholder="请输入B队名称" clearable />
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model="searchObj.status" placeholder="请选择状态" clearable style="width: 180px">
        <el-option label="未开始" value="0" />
        <el-option label="进行中" value="1" />
      </el-select>
    </el-form-item>
  </el-form>

  <el-form :inline="true">
    <el-form-item>
      <el-button type="primary" @click="handlerSearch">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column label="id" width="80">
      <template #default="scope">
        <el-tag>{{ scope.row.id }}</el-tag>
      </template>
    </el-table-column>
    <!-- 新增：赛事图片列 -->
    <el-table-column label="赛事图片" width="100">
      <template #default="scope">
        <el-avatar :src="scope.row.mimg" size="medium">
          <img src="@/assets/upload.png" alt="默认图片" v-if="!scope.row.mimg" />
        </el-avatar>
      </template>
    </el-table-column>
    <el-table-column label="赛事名称" width="200">
      <template #default="scope">
        <el-tag>{{ scope.row.name }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="场馆" width="150">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>场馆ID: {{ scope.row.stadiumId }}</div>
          </template>
          <template #reference>
            <el-tag>{{ getStadiumName(scope.row.stadiumId) }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column label="A队" width="120">
      <template #default="scope">
        <el-tag>{{ scope.row.teama }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="B队" width="120">
      <template #default="scope">
        <el-tag>{{ scope.row.teamb }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="比赛时间" width="180">
      <template #default="scope">
        <el-tag>{{ scope.row.matchTime }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="售票开始时间" width="180">
      <template #default="scope">
        <el-tag>{{ scope.row.ticketStarttime }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="售票结束时间" width="180">
      <template #default="scope">
        <el-tag>{{ scope.row.ticketEndtime }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="赛事信息" width="200">
      <template #default="scope">
        <el-tag>{{ scope.row.message }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="状态" width="100">
      <template #default="scope">
        <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
          {{ getStatusName(scope.row.status) }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[10, 20, 30, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

  <!-- 编辑对话框 -->
  <el-dialog v-model="editWinVisible" title="编辑赛事信息" width="600">
    <el-form
        ref="editFormRef"
        :model="obj"
        label-width="120px"
    >
      <el-form-item label="ID" disabled>
        <el-input v-model="obj.id" autocomplete="off" />
      </el-form-item>
      <!-- 新增：编辑表单图片上传 -->
      <el-form-item label="赛事图片">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img :src="obj.mimg ? obj.mimg : '@/assets/upload.png'"
               style="width: 100px; height: 100px; border-radius: 4px;"
               alt="赛事图片"/>
        </el-upload>
      </el-form-item>
      <el-form-item label="赛事名称">
        <el-input v-model="obj.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="场馆">
        <el-select
            v-model="obj.stadiumId"
            placeholder="请选择场馆"
            filterable
            style="width: 240px"
        >
          <el-option
              v-for="item in stadiums"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="A队">
        <el-input v-model="obj.teama" autocomplete="off" />
      </el-form-item>
      <el-form-item label="B队">
        <el-input v-model="obj.teamb" autocomplete="off" />
      </el-form-item>
      <el-form-item label="比赛时间">
        <el-date-picker
            v-model="obj.matchTime"
            type="datetime"
            placeholder="选择比赛时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="售票开始时间">
        <el-date-picker
            v-model="obj.ticketStarttime"
            type="datetime"
            placeholder="选择售票开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="售票结束时间">
        <el-date-picker
            v-model="obj.ticketEndtime"
            type="datetime"
            placeholder="选择售票结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="赛事信息">
        <el-input v-model="obj.message" autocomplete="off" type="textarea" :rows="3"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="obj.status" placeholder="请选择状态" style="width: 240px">
          <el-option label="未开始" value="0" />
          <el-option label="进行中" value="1" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editCancel">取消</el-button>
      <el-button type="primary" @click="editCommit">提交</el-button>
    </template>
  </el-dialog>

  <!-- 新增对话框 -->
  <el-dialog v-model="addWinVisible" title="新增赛事信息" width="600">
    <el-form
        ref="addFormRef"
        :model="obj"
        label-width="120px"
    >
      <!-- 新增：新增表单图片上传 -->
      <el-form-item label="赛事图片">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img :src="obj.mimg ? obj.mimg : '@/assets/upload.png'"
               style="width: 100px; height: 100px; border-radius: 4px;"
               alt="赛事图片"/>
        </el-upload>
      </el-form-item>
      <el-form-item label="赛事名称">
        <el-input v-model="obj.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="场馆">
        <el-select
            v-model="obj.stadiumId"
            placeholder="请选择场馆"
            filterable
            style="width: 240px"
        >
          <el-option
              v-for="item in stadiums"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="A队">
        <el-input v-model="obj.teama" autocomplete="off" />
      </el-form-item>
      <el-form-item label="B队">
        <el-input v-model="obj.teamb" autocomplete="off" />
      </el-form-item>
      <el-form-item label="比赛时间">
        <el-date-picker
            v-model="obj.matchTime"
            type="datetime"
            placeholder="选择比赛时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="售票开始时间">
        <el-date-picker
            v-model="obj.ticketStarttime"
            type="datetime"
            placeholder="选择售票开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="售票结束时间">
        <el-date-picker
            v-model="obj.ticketEndtime"
            type="datetime"
            placeholder="选择售票结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="赛事信息">
        <el-input v-model="obj.message" autocomplete="off" type="textarea" :rows="3"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="obj.status" placeholder="请选择状态" style="width: 240px">
          <el-option label="未开始" value="0" />
          <el-option label="进行中" value="1" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addCancel">取消</el-button>
      <el-button type="primary" @click="addCommit">提交</el-button>
    </template>
  </el-dialog>
</template>

<style></style>